package com.study.current.step1;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PrintABC {
    private final Lock lock = new ReentrantLock();
    Condition a = lock.newCondition();
    Condition b = lock.newCondition();
    Condition c = lock.newCondition();
    int flag = 0;
    int i = 10;

    public void PrintA(){
        lock.lock();
        try {
            while (i > 0){
                while (flag != 0){
                    a.await();
                }
                System.out.print("A");
                flag = 1;
                b.signal();
            }
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void PrintB(){
        lock.lock();
        try {
            while (i > 0){
                while (flag != 1){
                    b.await();
                }
                System.out.print("B");
                flag = 2;
                c.signal();
            }
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void PrintC(){
        lock.lock();
        try {
            while (i > 0){
                while (flag != 2){
                    c.await();
                }
                System.out.print("C");
                --i;
                Thread.sleep(1000);
                flag = 0;
                a.signal();
            }
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

}
